package com.glory.brepda.utils;

import android.graphics.Bitmap;
import android.util.Log;

import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;


public class SmbFileUtils {
//    public static String remoteUrl =
//            "smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/padpic/part/up/";   //大连
//
//    public static String remoteCrashUrl =
//            "smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/padpic/badpic/up/";   //大连异常联络
//
//    public static String remoteThumUrl =
//            "smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/padpic/part/sup/";   //大连  缩略图
//
//    public static String remoteCrashThumUrl =
//            "smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/padpic/badpic/sup/";   //大连异常联络  缩略图
//
//
//    public static String remoteBoxUrl =
//            "smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/padpic/part/ch/";   //大连  箱号图
//
//    public static String remoteBoxThumUrl =
//            "smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/padpic/part/chSup/";   //大连  箱号图

    public static String downLoadImage =
            "smb://administrator:fsbrec%403388@192.168.6.56/QCcraterInSpectionImage/";  //巨风

    /**
     * 读取所有文件
     * @param localDir
     * @return
     */
    public static List<SmbFile> getSmbFile(String localDir) {
        List<SmbFile> files = forFile(localDir);
        return files;
    }

    /**
     * 递归读取
     * @param localDir
     * @return
     */
    public static List<SmbFile> forFile(String localDir) {
        List<SmbFile> allfiles = new ArrayList<SmbFile>();
        try {
            SmbFile file = new SmbFile(localDir);
            if (file.exists()) {
                SmbFile[] files = file.listFiles();
                long ln = 10;
                for (SmbFile f : files) {
                    if (!f.isFile()) {
                        if(!"INSP_LABEL/".equals(f.getName()) && !"SHIP_BOX_LABEL/".equals(f.getName())){
                            allfiles.addAll(forFile(localDir + f.getName()));
                        }
                    } else {
                        if("csv".equals(f.getName().split("\\.")[1])){
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date cdate =new Date(f.createTime());
                            String cd = df.format(cdate);
                            Date currentTime = new Date();
                            String cn = df.format(currentTime);
                            if(getDistanceTimes(cd,cn)>ln){
                                allfiles.add(f);
                            }
                        }
                    }
                }
            }
        } catch (SmbException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return allfiles;
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param starttime 时间参数 1 格式：1990-01-01 12:00:00
     * @param endtime 时间参数 2 格式：2009-01-01 12:00:00
     * @return long[] 返回值为：{天, 时, 分, 秒}
     */
    public static long getDistanceTimes(String starttime, String endtime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(starttime);
            two = df.parse(endtime);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
//            day = diff / (24 * 60 * 60 * 1000);
//            hour = (diff / (60 * 60 * 1000) - day * 24);
//            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000);
//            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        long[] times = {day, hour, min, sec};
        return sec;
    }

    /**
     * 将本地文件上传到共享文件夹中
     */
//    public static String smbUpload(String mkdir, String localDir, String fileName) {
//        // 日志记录：原图开始上传
//        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "原图开始上传");
//
//        // 尝试上传文件
//        boolean success = false;
//        try {
//            // 构建远程文件路径
//            SmbFile remoteFile = new SmbFile(remoteUrl + mkdir + "/" + fileName + ".jpg");
//
//            // 检查文件是否已存在
//            if (remoteFile.exists()) {
//                return "文件已存在";
//            }
//
//            // 构建本地文件
//            File localFile = new File(localDir);
//
//            // 进行文件传输
//            try (InputStream in = new BufferedInputStream(new FileInputStream(localFile));
//                 OutputStream out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile))) {
//
//                byte[] buffer = new byte[4096];
//                int len;
//                while ((len = in.read(buffer)) > 0) {
//                    out.write(buffer, 0, len);
//                }
//
//                success = true; // 文件上传成功
//            }
//
//        } catch (Exception e) {
//            String msg = "发生错误：" + e.getMessage();
//            Log.e("TAG", "smbUpload: " + msg);
//            FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "失败原因" + msg);
//            return msg;
//
//        } finally {
//            // 日志记录：原图开始上传结束或失败
//            FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + (success ? "原图开始上传结束" : "原图开始上传失败"));
//        }
//
//        return "OK";
//    }

    public static String smbUploadFH(String mkdir,String localDir,String fileName) {
// 日志记录：原图开始上传
        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "原图开始上传");

// 尝试上传文件
        boolean success = false;
        try {
            // 检查远程文件夹是否存在，不存在则创建
            String mkDirResult = smbMkDir("smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/", mkdir);
            if (!mkDirResult.equals("OK")) {
                return "文件夹建立失败，报错信息：" + mkDirResult;
            }

            // 构建本地文件和远程文件
            File localFile = new File(localDir);
            SmbFile remoteFile = new SmbFile("smb://MES:a*1@192.168.1.186/mes-tab/Tcard/DLXJ_Tcard/" + mkdir + "/" + fileName + ".jpg");

            // 进行文件传输
            try (InputStream in = new BufferedInputStream(new FileInputStream(localFile));
                 OutputStream out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile))) {

                byte[] buffer = new byte[4096];
                int len;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }

                success = true; // 文件上传成功
            }

        } catch (Exception e) {
            String msg = "发生错误：" + e.getMessage();
            Log.e("TAG", "smbUpload: " + msg);
            FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "失败原因" + msg);
            return msg;

        } finally {
            // 日志记录：原图开始上传结束或失败
            FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + (success ? "原图开始上传结束" : "原图开始上传失败"));
        }

        return "OK";
    }


    /**
     * 将多个本地文件上传到共享文件夹中
     */
//    public static boolean smbUploadThum(String mkdir, Bitmap bitmap, String fileName) {
//        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "缩略图开始上传");
//        boolean success;
//        InputStream in = null;
//        OutputStream out = null;
//        try {
//            // 获取
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            bitmap.compress(Bitmap.CompressFormat.JPEG,10,baos);
//            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
//
//
//
//            SmbFile remoteFile = new SmbFile(remoteThumUrl + mkdir + "/"+ fileName + ".jpg");
//            if (remoteFile.exists()) {
//                return true;
//            }
//            remoteFile.connect(); // 尝试连接
//
//            in = new BufferedInputStream(inputStream);
//            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
//
//            byte[] buffer = new byte[4096];
//            int len = 0; // 读取长度
//            while ((len = in.read(buffer, 0, buffer.length)) != -1) {
//                out.write(buffer, 0, len);
//            }
//            out.flush(); // 刷新缓冲的输出流
//            success = true;
//        } catch (Exception e) {
//            String msg = "发生错误：" + e.getLocalizedMessage();
//            Log.e("TAG", "smbUpload: " + msg);
//            System.out.println(msg);
//            success = false;
//        } finally {
//            try {
//                if (out != null) {
//                    out.close();
//                }
//                if (in != null) {
//                    in.close();
//                }
//            } catch (Exception e) {
//                success = false;
//            }
//
//        }
//        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + (success ? "缩略图开始上传结束" : "缩略图开始上传失败"));
//        return success;
//    }


    /**
     * 将本地文件上传到共享文件夹中
     */
//    public static boolean smbCrashUpload(String mkdir,Bitmap bitmap,String localDir,String fileName) {
//        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "原图开始上传");
//        boolean success;
//        InputStream in = null;
//        OutputStream out = null;
//        InputStream inputStream = null;
//        File localFile = null;
//        try {
//            // 获取
//            if (bitmap == null){
//                localFile = new File(localDir);
//                smbMkDir(remoteCrashUrl,mkdir);
//            }else {
//                ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
//                inputStream = new ByteArrayInputStream(baos.toByteArray());
//                smbMkDir(remoteCrashUrl,mkdir);
//            }
//            SmbFile remoteFile = new SmbFile(remoteCrashUrl + mkdir + "/"+ fileName + ".jpg");
//            remoteFile.connect(); // 尝试连接
//            // 获取
//            if (remoteFile.exists()) {
//                return true;
//            }
//            in = new BufferedInputStream(bitmap == null ? new FileInputStream(localFile) : inputStream);
//            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
//
//            byte[] buffer = new byte[4096];
//            int len = 0; // 读取长度
//            while ((len = in.read(buffer, 0, buffer.length)) != -1) {
//                out.write(buffer, 0, len);
//            }
//            out.flush(); // 刷新缓冲的输出流
//            success = true;
//        } catch (Exception e) {
//            String msg = "发生错误：" + e.getLocalizedMessage();
//            Log.e("TAG", "smbUpload: " + msg);
//            System.out.println(msg);
//            success = false;
//        } finally {
//            try {
//                if (out != null) {
//                    out.close();
//                }
//                if (in != null) {
//                    in.close();
//                }
//            } catch (Exception e) {
//                success = false;
//            }
//
//        }
//        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + (success ? "原图开始上传结束" : "原图开始上传失败"));
//        return success;
//    }


    /**
     * 将多个本地文件上传到共享文件夹中
     */
//    public static boolean smbCrashUploadThum(String mkdir, Bitmap bitmap, String fileName) {
//        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "缩略图开始上传");
//        boolean success;
//        InputStream in = null;
//        OutputStream out = null;
//        try {
//            // 获取
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            bitmap.compress(Bitmap.CompressFormat.JPEG,10,baos);
//            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
//            smbMkDir(remoteCrashThumUrl,mkdir);
//            SmbFile remoteFile = new SmbFile(remoteCrashThumUrl + mkdir + "/"+ fileName + ".jpg");
//
//            remoteFile.connect(); // 尝试连接
//            if (remoteFile.exists()) {
//                return true;
//            }
//            in = new BufferedInputStream(inputStream);
//            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
//
//            byte[] buffer = new byte[4096];
//            int len = 0; // 读取长度
//            while ((len = in.read(buffer, 0, buffer.length)) != -1) {
//                out.write(buffer, 0, len);
//            }
//            out.flush(); // 刷新缓冲的输出流
//            success = true;
//        } catch (Exception e) {
//            String msg = "发生错误：" + e.getLocalizedMessage();
//            Log.e("TAG", "smbUpload: " + msg);
//            System.out.println(msg);
//            success = false;
//        } finally {
//            try {
//                if (out != null) {
//                    out.close();
//                }
//                if (in != null) {
//                    in.close();
//                }
//            } catch (Exception e) {
//                success = false;
//            }
//
//        }
//        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + (success ? "缩略图开始上传结束" : "缩略图开始上传失败"));
//        return success;
//    }


    /**
     * 将文件从共享文件夹中下载下来到本地
     *
     * @param remoteUrl
     * @param localDir
     */
    public static boolean smbGet(String remoteUrl, String localDir) {
        if (remoteUrl.isEmpty()){
            return true;
        }
        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), remoteUrl + "图片开始下载");
        boolean success;
        InputStream in = null;
        OutputStream out = null;
        try {
            SmbFile remoteFile = new SmbFile(remoteUrl);

            if (remoteFile == null) {
                System.out.println("共享文件不存在");
                return false;
            }
            String fileName = remoteFile.getName();
            // 创建文件夹(根目录下直接创建文件可以直接new
            // File，如果是多层目录下文件的创建，需要先创建多层文件夹，然后用输入流在文件夹相应目录下再将文件建立)
            File localFile = new File(localDir + File.separator);
            if (!localFile.exists()) {// 如果文件夹不存在
                // 创建文件夹，mkdir是创建根目录，mkdirs创建多层目录
                localFile.mkdirs();
            }
            // 创建文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(localDir + File.separator + fileName));
            bw.close();
            File localFiles = new File(localDir + File.separator + fileName);
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(localFiles));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            try {
                if (out != null)      out.close();
                if (in != null)     in.close();
            } catch (Exception e) {
                e.printStackTrace();
                success = false;
            }
        }
        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), remoteUrl + (success ? "图片开始下载结束" : "图片开始下载失败"));
        return success;
    }

    /**
     * 创建文件夹
     *
     * @param remoteUrl
     * @return
     */
    public static String smbMkDir(String remoteUrl, String path) {
        SmbFile smbFile;
        try {
            // 初始化远程路径
            String[] paths = path.split("/");
            for (String str : paths) {
                    remoteUrl = remoteUrl + "/" + str;
                    smbFile = new SmbFile(remoteUrl);
                    if (!smbFile.exists()) {
                        smbFile.mkdir();
                    }
            }
            return "OK"; // 如果所有路径都创建成功，返回 "OK"
        } catch (MalformedURLException | SmbException e) {
            e.printStackTrace();
            return e.getMessage(); // 返回异常信息
        }
    }

    /**
     * 删除文件
     *
     * @param remoteUrl
     */
    public static void deleteFile(String remoteUrl) {
        SmbFile SmbFile;
        try {
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            SmbFile = new SmbFile(remoteUrl);
            if (SmbFile.exists()) {
                SmbFile.delete();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }

    /**
     * GBK转UTF8
     */
    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }


    /**
     * 将本地文件上传到共享文件夹中
     */
    public static boolean smbUploadForUrl(String mkdir,String localDir,String fileName,String remoteurl) {
        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "原图开始上传");
        boolean success;
        InputStream in = null;
        OutputStream out = null;
        try {
            // 获取
            File localFile = new File(localDir);
            smbMkDir(remoteurl,mkdir);
            SmbFile remoteFile = new SmbFile(remoteurl + mkdir + "/"+ fileName + ".jpg");
            remoteFile.connect(); // 尝试连接

            in = new BufferedInputStream(new FileInputStream(localFile));
            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));

            byte[] buffer = new byte[4096];
            int len = 0; // 读取长度
            while ((len = in.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush(); // 刷新缓冲的输出流
            success = true;
        } catch (Exception e) {
            String msg = "发生错误：" + e.getLocalizedMessage();
            Log.e("TAG", "smbUpload: " + msg);
            System.out.println(msg);
            success = false;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                success = false;
            }

        }
        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + (success ? "原图开始上传结束" : "原图开始上传失败"));
        return success;
    }

    /**
     * 将多个本地文件上传到共享文件夹中
     */
    public static boolean smbUploadThumForUrl(String mkdir, Bitmap bitmap, String fileName,String remoteurl) {
        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + "缩略图开始上传");
        boolean success;
        InputStream in = null;
        OutputStream out = null;
        try {
            // 获取
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,10,baos);
            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
            smbMkDir(remoteurl,mkdir);
            SmbFile remoteFile = new SmbFile(remoteurl + mkdir + "/"+ fileName + ".jpg");

            remoteFile.connect(); // 尝试连接

            in = new BufferedInputStream(inputStream);
            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));

            byte[] buffer = new byte[4096];
            int len = 0; // 读取长度
            while ((len = in.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush(); // 刷新缓冲的输出流
            success = true;
        } catch (Exception e) {
            String msg = "发生错误：" + e.getLocalizedMessage();
            Log.e("TAG", "smbUpload: " + msg);
            System.out.println(msg);
            success = false;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                success = false;
            }

        }
        FreeApi_LogUtils.saveErrorMessages(FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd hh:MM:ss"), fileName + (success ? "缩略图开始上传结束" : "缩略图开始上传失败"));
        return success;
    }
}
